package com.lanou3g.hw0517.view;

import com.lanou3g.hw0517.commons.Constant;
import com.lanou3g.hw0517.pojo.User;
import com.lanou3g.hw0517.util.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "resultServlet", urlPatterns = "/result")
public class resultServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String keyword = request.getParameter("keyword");
        String sql = "select * from users where username like " + "'%" + keyword + "%'";
        PreparedStatement statement = JDBCUtil.getPreStatement(sql);
        ResultSet rs = null;
        List<User> users = new ArrayList<>();
        try {
            rs = statement.executeQuery();
            while (rs.next()) {
                String username = rs.getString("username");
                String nickname = rs.getString("nickname");
                String sex = rs.getString("sex");
                String hobby = rs.getString("hobby");

                User user = new User();

                user.setUsername(username);
                user.setNickname(nickname);
                user.setHobby(hobby);
                user.setSex(sex);
                users.add(user);
            }
            statement.close();
            rs.close();
            request.setAttribute("users", users);
            request.getRequestDispatcher("/result.jsp").forward(request, response);
        } catch (SQLException e) {
            e.printStackTrace();
        }


    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
